<template>
  <div class="app-container">
    <el-container>

      <el-header class="filter-container" style="margin-bottom: 0px">

        <div>

          <!--          <div class="tool-bar1" style="width: 100%; margin-bottom: 10px">-->
          <!--          <el-row v-if="isUpload">-->
          <!--            <upload-excel-component style="text-align: center" :tape-data="temper" :on-change="handleSuccessExcel"  />-->
          <!--          </el-row>-->
<!--          <el-row>-->

<!--            <el-button type="primary" icon="el-icon-top-right" @click="onExport(0)" class="filter-item">批量导出</el-button>-->
<!--            <el-button type="primary" icon="el-icon-bottom-left" @click="onImport(0)" class="filter-item">批量导入-->
<!--            </el-button>-->
<!--            &lt;!&ndash;            <el-button type="primary"  @click="toggleSelection()" class="filter-item">取消选择</el-button>&ndash;&gt;-->

<!--            <el-link type="primary" style="margin-left: 20px;color:blue;">下载学生信息模板</el-link>-->
<!--          </el-row>-->
          <!--          </div>-->
          <!--          <div class="tool-bar2" style="width: 100%; margin-bottom: 10px">-->
          <el-row >
            <el-popover placement="bottom" trigger="click" style="text-align: center">
              <el-button plain slot="reference" @click="onCheckTitle">
                表头<i class="el-icon-caret-bottom el-icon--right"/>
              </el-button>
              <ul v-if="isShowTitleList" style="list-style-type:none"></ul>

              <ul style="list-style-type:none">
                <li style="margin-bottom: 10px">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="handleCheckAllChange">全选
                  </el-checkbox>
                </li>
                <li v-for="(item,index) in titleList">
                  <el-checkbox v-model="item.checked" :label="item.label" @change="handleCheckedOption"
                               :disabled="isFixTitle(item)"></el-checkbox>
                </li>
              </ul>
              <!--              <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="handleCheckAllChange">全选 </el-checkbox>-->
              <!--              <el-checkbox-group v-model="checkTitleList" @change="handleCheckedBoxGroup">-->
              <!--                <el-checkbox v-for="(item,index) in titleList" :label="item.label" :key="item.key" v-model="item.label"-->
              <!--                             @change="handleCheckedOption" style="display:block;"></el-checkbox>-->
              <!--              </el-checkbox-group>-->
              <!--              @click="onCheckTitle"-->

              <!--              <el-button plain slot="reference" @click="onCheckTitle">-->
              <!--                表头<i class="el-icon-caret-bottom el-icon&#45;&#45;right"/>-->
              <!--              </el-button>-->
            </el-popover>
            <el-select v-model="condition.tenantid" placeholder="组织结构" :clearable="true">
              <el-option
                v-for="item in organizeList"
                :key="item.id"
                :label="item.tenantName"
                :value="item.tenantId">
              </el-option>
            </el-select>
            <el-select v-model="condition.basecode" placeholder="年级" :clearable="true" style="width: 100px">
              <el-option
                v-for="item in GRADE"
                :key="item.id"
                :label="item.label"
                :value="item.kcode">
              </el-option>
            </el-select>
            <el-select v-model="condition.classcode" placeholder="班级" :clearable="true" style="width: 120px">
              <el-option
                v-for="item in BIND_STATUS"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="condition.combocode" placeholder="套餐" :clearable="true" style="width: 120px">
              <el-option v-for="(item,index) in orderType"
                         :label="item.name"
                         :value="item.kcode">
              </el-option>
            </el-select>

            <el-input v-model="inputStr" placeholder="绑定码/姓名" style="width: 200px; "></el-input>
            <el-button type="primary" icon="el-icon-search" @click="onSearch()" style="width: 90px;">搜索</el-button>
<!--            <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" style="margin-left:50px">添加</el-button>-->
            <el-button type="warning" icon="el-icon-top-right" @click="onExport(0)" class="filter-item" style="float: right">批量导出</el-button>
          </el-row>
        </div>


      </el-header>
      <el-main >
        <el-table
          ref="singleTable"
          :data="temperList"
          v-loading="listLoading"
          style="margin-top:0px; "
          highlight-current-row
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#e1e4e5',color:'#80878f'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left">

          </el-table-column>
          <el-table-column align="center" v-for="(item,index) in checkTitleList" :label="item.label" :key="item.key"
                           min-width="80px">
            <template slot-scope="scope">
              {{ scope.row[item.value] }}

<!--              <p v-if="item.label==='组织结构'">-->
<!--                {{ organizeList[organize_id].label }}-->
<!--              </p>-->
<!--              <p v-else-if="item.label==='年级'">{{ GRADE[scope.row[item.value]].label }}</p>-->
<!--              <p v-else-if="item.label==='班级'">{{ CLASS[scope.row[item.value]].label }}</p>-->



<!--              <p v-else-if="item.label==='绑定状态'">-->
<!--                <el-tag-->
<!--                  :type="BIND_STATUS[scope.row[item.value]].type"-->
<!--                >-->
<!--                  {{ BIND_STATUS[scope.row[item.value]].label }}-->
<!--                </el-tag>-->
<!--              </p>-->

<!--              <p v-else-if="item.label==='支付状态'">-->
<!--                <el-tag-->
<!--                  :type="PAY_STATUS[scope.row[item.value]].type"-->
<!--                >-->
<!--                  {{ PAY_STATUS[scope.row[item.value]].label }}-->
<!--                </el-tag>-->
<!--              </p>-->
<!--              <p v-else-if="item.label==='用户状态'">-->
<!--                <el-switch-->
<!--                  v-model="scope.row.active==1"-->
<!--                  :width="60"-->
<!--                  active-text="启用"-->
<!--                  inactive-text="禁用"-->
<!--                  :class="switchs"-->
<!--                  @change="handleModifyStatus(scope.row)"-->
<!--                >-->

<!--                </el-switch>-->

<!--              </p>-->
<!--              <p v-else> {{ scope.row[item.value] }}</p>-->

            </template>
          </el-table-column>


<!--          <el-table-column align="center" label=操作 width="270" fixed="right">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button type="primary" size="small" @click="handleEdit(scope.row)" disabled>编辑</el-button>-->
<!--              <el-button size="small" :type="PAY_STATUS[scope.row.pay_status].type" @click="handlePayStatus(scope.row)">-->
<!--                {{ PAY_STATUS[scope.row.pay_status].label }}-->
<!--              </el-button>-->
<!--              <el-button type="danger" size="small" @click="handleDelete(scope.row,scope.$index)" disabled>删除</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>

<!--        <el-pagination-->
<!--          @size-change="handleSizeChange"-->
<!--          @current-change="handleCurrentChange"-->
<!--          :current-page="currentPage4"-->
<!--          :page-sizes="[100, 200, 300, 400]"-->
<!--          :page-size="100"-->
<!--          layout="total, sizes, prev, pager, next, jumper"-->
<!--          :total="400">-->
<!--        </el-pagination>-->

        <!--      创建用户面板-->


        <!--      批量上传面板-->
        <el-drawer

          :visible.sync="isUpload"
          direction="ttb"
          :before-close="handleCloseUpload"
          size="50%">
          <upload-excel-component style="text-align: center" :tape-data="temper" :on-change="handleSuccessExcel"/>

          <!--          <upload-excel-component style="text-align: center" :tape-data="tapeDateExcel" :on-change="handleSuccessExcel"  />-->
        </el-drawer>


      </el-main>

    </el-container>
  </div>
</template>

<script>
import Link from '@/layout/components/Sidebar/Link'
import switchs from '@/styles/switch.scss'
import {
  addStudent,
  deleteParent,
  deleteStudent,
  getParents,
  getStudents,
  updateParent,
  updateStudent
} from '@/api/student'
import { isInteger } from '@/utils/validate'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { parseTime } from '@/utils'
import { getCondition } from '@/api/payorders'
import { getOrders } from '@/api/basicmgt'
import { mapGetters } from 'vuex'

const defaultTemper = {
  id: '',
  studentname: '',
  basename: '',
  classname: '',
  comboname: '',
  payamount: '',
  tenantname: '',
  parentname: '',
  parenttal: '',
  openid: '',
  createtime: '',
  expiretime: '',
}

const defaultCondition = {
  id: '',
  tenantid: '',
  basecode: '',
  classcode: '',
  studentname: '',
  combocode: '',
  studentcode: '',
  parenttal: '',
  starttime: '',
  endstime: '',

}

const organize = [
  { id: '0', label: '未选择' },
  { id: '1', label: '汉唐和雅' },
  { id: '2', label: '金马小学' },
  { id: '3', label: '高新区试验小学' }
]

const classList = [
  { id: '0', label: '未选择' },
  { id: '1', label: '1' },
  { id: '2', label: '2' },
  { id: '3', label: '3' },
  { id: '4', label: '4' },
  { id: '5', label: '5' }
]

const defaultTitleName = [
  { key: 0, value: 'id', label: 'ID', width: 50, checked: true },
  { key: 1, value: 'studentname', label: '姓名', width: 120, checked: true },
  { key: 2, value: 'basename', label: '年级', width: 220, checked: true },
  { key: 3, value: 'classname', label: '班级', width: 120, checked: true, disabled: true },
  { key: 4, value: 'comboname', label: '套餐', width: 100, checked: true, disabled: true },
  { key: 5, value: 'payamount', label: '金额', width: 80, checked: true, disabled: true },
  { key: 6, value: 'tenantname', label: '组织结构', width: 80, checked: true, disabled: true },
  { key: 7, value: 'parentname', label: '家长', width: 129, checked: true, disabled: true },
  { key: 8, value: 'parenttal', label: '电话', width: 80, checked: true },
  { key: 9, value: 'openid', label: '微信ID', width: 220, checked: true },
  { key: 10, value: 'createtime', label: '支付时间', width: 150, checked: true },
  { key: 11, value: 'expiretime', label: '到期时间', width: 150, checked: true },
  // { key: 12, value: 'expiretime', label: '绑定状态', width: 150, checked: true },
  // { key: 13, value: 'bindcode', label: '绑定码', width: 150, checked: true },
  // { key: 14, value: 'pay_status', label: '支付状态', width: 150, checked: true },
  // { key: 15, value: 'address', label: '地址', width: 220, checked: true },
  // { key: 16, value: 'describe', label: '备注', width: 220, checked: true },
  // { key: 17, value: 'active', label: '用户状态', width: 120, checked: true },
]

const defaultCheckFixTitle = [
  '姓名',
  '年级',
  '班级',
  '租户名称',
]
/***
 * 家长角色数据对象模型
 * @type {{openid: string, name: string, educode: string, tel: string, id: string, bindcode: string, parentid: string}}
 */
const defaultRoleParentNameModel = {
  id: '-1',
  bindcode: '',
  educode: '',
  name: '',
  parentid: '0',
  tel: '',
  openid: ''
}

export default {
  name: 'students',
  components: { Link, UploadExcelComponent },
  data() {
    return {

      rules: {
        order_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        order_type: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
        price: [{ required: true, message: '请输入数字', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }]
      },
      input_toolbar: '',
      isUpload: false,

      isShowTitleList: true,

      dialogTitle: ['创建', '编辑'],
      temper: Object.assign({}, defaultTemper),
      temperList: [],
      tableHeader: [],
      roleList: [],
      dialogVisible: false,
      dialogType: '0',
      organize_id: 0,//组织机构id
      organizeList: organize,//组织机构列表

      titleList: defaultTitleName,
      checkTitleList: defaultTitleName,

      isCheckAll: true,//表头项，全选状态
      isIndeterminate: false,
      //这两个新增参数是在导出学生数据时追加的
      // headerPush:['组织结构','激活状态'],
      // filterValPush:['organize','active'],

      props: { multiple: true, emitPath: false },

      str_tableRowClassName: '',

      tempGrade: '',
      tempClass: '',
      tempOrganize_id: '',
      bindId: '',
      payid: '',

      parentList: [],
      isParentListEdit: [],
      isShowParentList: false,
      ROLE_PARENTS_NAME: this.$global.ROLE_PARENTS_NAME,

      BIND_STATUS: this.$global.BIND_STATUS,
      PAY_STATUS: this.$global.PAY_STATUS,

      GRADE: [],
      CLASS: classList,
      ACTIVE: this.$global.ACTIVE,
      orderType:[],

      selectList: '',
      multipleSelection: [],
      downloadLoading: false,
      filename: 'students',//文件名称

      //----excel相关-----------
      uploadfiles: [],
      tapeDateExcel: {//上传excel时用到的部分参数
        actid: '',
        name: '题库',//固定名称
        codename: 'qusbank',//固定名称
        url: '',             //此项未空
        auther: 'cxy',
        excelurl: 'this.pt_type.server',        //excel保存的路径
        modifytime: parseTime(new Date()),
        platform: 'this.platformKey'
      },

      switchs: switchs,
      /**
       * 筛选条件
       * */
      condition:defaultCondition,
      inputStr:'',
      listLoading:false,

    }

  },

  created() {

    this.getOrders()
    this.getCondition()

  },

  computed: {

    ...mapGetters([
      'name',
      'avatar',
      'user_organize',
      'user_role',
      'user_routes'
    ]),

    isDisable:{
      get() {
        return this.user_role=="RA0003"?true:false
      },
      set(val) {
      }
    }
  },
  watch: {},

  methods: {





    /**
     * 表头切换
     */
    handleCheckAllChange(val) {
      console.log('handleCheckAllChange==' + val)
      // this.checkTitleList = this.titleList.filter(function(obj, index) {
      //     obj.cheched = this.isCheckAll
      //   return obj.checked
      // })

      this.checkTitleList = []
      for (let index in this.titleList) {
        if (!val) {
          let bool = defaultCheckFixTitle.some((value) => {
            // console.log("value="+value)
            return value == this.titleList[index].label
          })
          if (bool) {
            this.titleList[index].checked = true
            this.checkTitleList.push(this.titleList[index])
          } else {
            this.titleList[index].checked = val
          }

        } else {
          this.titleList[index].checked = val
          this.checkTitleList.push(this.titleList[index])
        }
      }

      // this.checkTitleList = val ? this.titleList : []
      this.isIndeterminate = false

      // if(this.isCheckAll){
      //   for (let item in this.checkTitleList) {
      // item.checked = val
      // console.log("item.checked=="+JSON.stringify(this.checkTitleList))
      // }
      // }

    },

    handleCheckedBoxGroup(value) {

      let checkedCount = value.length
      this.isCheckAll = checkedCount === this.checkTitleList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkTitleList.length

      // console.log("check-group onchange =="+JSON.stringify(value))

    },

    isFixTitle(item) {

      let bool = defaultCheckFixTitle.some(function(value) {
        return value == item.label
      })
      return bool
    },

    handleCheckedOption(val) {
      // console.log("handleCheckedOption onchange =="+val)
      this.checkTitleList = this.titleList.filter(function(obj, index) {

        return obj.checked

      })

      let checkedCount = this.checkTitleList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.titleList.length

      // console.log("handleCheckedOption onchange =="+checkedCount+"  ")

    },
    isCheck(val) {
      // if (this.checkTitleList.length > 0) {
      //   let arr = this.checkTitleList
      //   return arr.some(function(obj, index, arr) {
      //
      //     return obj.label == val
      //   })
      // } else {
      //   return false
      // }
// console.log("check-box onchange ")
    },

    onCheckTitle() {
      this.isShowTitleList = this.isShowTitleList ? false : true

      // console.log("item.checked=2="+JSON.stringify(this.checkTitleList))

    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    tableRowClassName({ row, rowIndex }) {
      if (row.active == 0) {
        return this.str_tableRowClassName
      }
      // return 'alive-row';

      // let self = this
      // for(let i=0;i<self.selectList.length;i++) {
      //   console.log("rowIndex="+rowIndex+"   "+self.selectList[i])
      //
      //   if (rowIndex === self.selectList[i]) {
      //     return 'alive-row';
      //   }
      // }
    },
    onSearch() {
      this.chechChinese()
      this.getCondition()
    },

    chechChinese(){
        if(/.*[\u4e00-\u9fa5]+.*$/.test(this.inputStr)){
          this.condition.studentname = this.inputStr
        }else{
          this.condition.studentcode = this.inputStr
        }
    },

    onCreate(type) {

      this.dialogType = 0
      this.dialogVisible = true
      this.$nextTick(() => {
        this.temper = Object.assign({}, defaultTemper)
      })

      console.log('onCreate==' + JSON.stringify(this.temper))

    },
    handleCloseUpload(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },

    handleSuccessExcel({ results, header }) {
      this.temperList = results
      console.log('上传Excel=' + JSON.stringify(results[0]))
      this.tableHeader = header
    },

    beforeUploadExcel(file) {
      this.uploadfiles = file
      console.log('this.uploadfiles==' + this.uploadfiles[0])
      const isLt1M = file.size / 1024 / 1024 < 10

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '最大不超过10M',
        type: 'warning'
      })
      return false
    },

    onImport(type) {
      this.isUpload = this.isUpload ? false : true
      // this.getHeaderExcel(this.checkTitleList,"label")

    },

    onExport(type) {
      if (this.multipleSelection.length) {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
          // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
          const tHeader = this.getHeaderExcel(this.checkTitleList, 'label')
          // tHeader.push('激活状态')
          const filterVal = this.getHeaderExcel(this.checkTitleList, 'value')
          // filterVal.push('active')
          const list = this.multipleSelection
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename
          })
          this.$refs.singleTable.clearSelection()
          this.downloadLoading = false
        })
      } else {
        this.$message({
          message: '请选择要导出的数据',
          type: 'warning'
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    handleEdit(item) {
      this.dialogType = 1
      this.dialogVisible = true
      this.temper = item
    },

    handleDelete(item, index) {
      console.log('index==' + index)

      this.$confirm('确定要删除此条信息吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteStudent(item.key)
        this.temperList.splice(index, 1)
        this.$message({
          type: 'success',
          message: 'Delete success !'
        })
      })
        .catch(err => {
          console.error(err)
        })

    },

    cancelDialog(fromname) {
      this.dialogVisible = false
      this.$refs[fromname].resetFields()
    },

    async confirmDialog(_dialogType) {

      let diaType = this.dialogType

      if (diaType == 0) {//创建
        const { data } = await addStudent(this.temper)
        this.temper.key = data.key
        console.log('temper==' + JSON.stringify(this.temper))
        this.temperList.push(this.temper)

      } else {
        await updateStudent(this.temper.key, this.temper)

        for (let index = 0; index < this.temperList.length; index++) {
          if (this.temperList[index].key === this.temper.key) {
            this.temperList.splice(index, 1, Object.assign({}, this.temper))
            break
          }
        }
      }

      // this.cancelDialog('studentFrom')
      this.dialogVisible = false
      console.log('temper=tel=' + this.temper.tel)
    },
    async getOrders() {
      const res = await getOrders()
      let orderList = res.data

      // console.log("tancan=="+JSON.stringify(res.data))

      this.$global.ORDER_TYPE = []
      for (let i = 0; i < orderList.length; i++) {
        this.$global.ORDER_TYPE.push(orderList[i])
      }
      this.orderType = this.$global.ORDER_TYPE
    },
    async getCondition() {
      this.GRADE = await this.$global.GRADE_SYS()
      this.organizeList = await this.$global.ORGANIZELIST()//组织机构列表
      this.listLoading = true;
      if(this.condition.tenantid!=null&&this.condition.tenantid!=""){
        getCondition(this.condition).then(
          res=>{
            this.temperList = res.data
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
        },
          ()=>{
            this.listLoading = false
          })


      }else{
        this.listLoading = false
      }
      // this.GRADE = await this.$global.GRADE_SYS()
      // const res = await getCondition(this.organize_id)
      // this.temperList = res.data
    },
    async getRoleParent(bindcode) {
      const res = await getParents(bindcode)
      this.parentList = res.data
      this.isParentListEdit = []
      for (let index in this.parentList) {
        this.isParentListEdit.push(false)
      }
    },

    handlePayStatus(row) {

      // row.pay_status = row.pay_status == 0 ? 1 : 0

      this.$message({
        message: '只可远观不可亵玩',
        type: 'warning'
      })


    },

    getHeaderExcel(array, value) {

      let arr = []
      array.forEach(e => {
        if (e.checked) {
          arr.push(e[value])
        }
      })

      // let arr = array.filter(function(item) {
      //
      //   return item[value]
      // });

      // console.log("Excel Header=="+JSON.stringify(arr))
      return arr

    }

  }

}
</script>

<style scoped>
.filter-item {
  /*float: right;*/
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .alive-row {
  /*background: #dc707d;*/
  background: #DCDFE6;
}

/*.upload-demo {*/
/*  text-align: center;*/
/*  vertical-align: middle;*/
/*  margin-top: 0;*/
/*  width: 50%;*/
/*}*/


</style>
<style>
.el-table th {
  display: table-cell !important;
}


</style>
